import os
from flask import jsonify, request
import requests
from openai import OpenAI
import sqlite3
from functools import wraps

# 数据库连接工具
def get_db_connection():
    """
    获取SQLite数据库连接
    :return: 数据库连接对象
    """
    db_path = os.path.join(os.path.dirname(__file__),  'database', 'app.db')
    if not os.path.exists(db_path):
        raise FileNotFoundError(f"Database file not found at {db_path}")
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    return conn

# API密钥验证装饰器
def api_key_required(f):
    """
    验证API密钥的装饰器
    :param f: 被装饰的函数
    :return: 装饰后的函数
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        api_key = request.headers.get('X-API-KEY')
        if not api_key:
            return jsonify({'error': 'API key is missing'}), 401
            
        conn = get_db_connection()
        user = conn.execute('SELECT * FROM users WHERE api_key = ?', (api_key,)).fetchone()
        conn.close()
        
        if user is None:
            return jsonify({'error': 'Invalid API key'}), 401
            
        return f(*args, **kwargs)
    return decorated_function

# 阿里大模型调用函数
def call_ali_model(prompt):
    """
    调用阿里云百炼API
    :param prompt: 用户输入的提示词
    :return: 模型生成的响应
    """
    api_key = os.getenv("DASHSCOPE_API_KEY")
    # 打印 API 密钥
    print(f"API Key: {api_key}")
    if not api_key:
        return {"error": "DASHSCOPE_API_KEY environment variable not set"}
    sys_prompt = '''
    你是一个原神可莉，你会根据用户的输入，生成原神可莉的回复。
    '''

        
    client = OpenAI(
        api_key=api_key,
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
    )
    completion = client.chat.completions.create(
        model="qwen-plus",
        messages=[{'role': 'system', 'content': sys_prompt},
                 {'role': 'user', 'content': prompt}],
        stream=True,
        stream_options={"include_usage": True}
    )
    return completion